import java.awt.Color;


public class Sphere implements Renderable {
	
	private final double cx;
	private final double cy;
	private final double cz;
	private final double radius;
	private final int material;
	
	public Sphere(double cx, double cy, double cz, double radius, int material){
		this.cx=cx;
		this.cy=cy;
		this.cz=cz;
		this.radius=radius;
		this.material=material;
	}
	
	public double getcx(){
		return cx;
	}

	public double getcy(){
		return cy;
	}
	
	public double getcz(){
		return cz;
	}
	
	public double getRadius(){
		return radius;
	}
	
	public int getMaterial(){
		return material;
	}

	
	@Override
	public double intersect(Ray r) {
		
		double dx = cx - r.getOrigin().getvx();
		double dy = cy - r.getOrigin().getvy();
		double dz = cz - r.getOrigin().getvz();
		Vector L = new Vector(dx,dy,dz);
	    double Tca = L.dotProduct(r.direction);
	    
	    if (Tca<0){
	    	return Double.MAX_VALUE;
	    }
	    
	    double d2 = L.dotProduct(L)-(Tca*Tca);
	    if(d2 > radius*radius){
	    	return Double.MAX_VALUE;
	    }
	    
        double Thc = Math.sqrt(radius*radius - d2);
        
        if(Tca-Thc<0 || Tca+Thc<0) return Double.MAX_VALUE;
        return (Tca-Thc);
    
    }
	
	
	
	public Vector getNormal(Vector vector) {
        return vector.subtructVector(getCenterVector()).normalizedVector();
    }

	
	
	@Override
	public double getT(Ray ray) {
		Vector vector = ray.getDirection();
		Vector point0 = ray.getOrigin();
		Vector r = getCenterVector().subtructVector(point0);
		double tDot = r.dotProduct(vector);
		
		if (tDot < 0)
			return -1;
		
		double dSquare = r.dotProduct(r) - Math.pow(tDot, 2);
		double rSquare = Math.pow(getRadius(), 2);
		if (dSquare > rSquare){
			return -1;
		}
		
		double t = Math.sqrt(rSquare - dSquare);
		
		if ((tDot - t) < 0)
			return tDot + t;
		
		if ((tDot + t) < 0)
			return tDot - t;
		
		return Math.min(tDot - t, tDot + t);
	}
	
	
	public Vector getCenterVector(){
		return new Vector(cx,cy,cz);
	}
	
}
